package net.discard.controller;

import com.alibaba.fastjson.JSONObject;
import net.discard.dao.UserRepository;
import net.discard.model.User;
import net.discard.model.domian.ResponseVo;
import net.discard.service.WXService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author Discard
 * @date 06/02/2115:10
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private WXService wxService;

    @GetMapping(value = "/getUser")
    public String getUserByCode(String code) {
        // 获取用户openid
        String openId = wxService.getOpenId(code);
        User user = userRepository.findByOpenid(openId);
        if (user != null) {
            return new ResponseVo(user).toString();
        }else {
            return new ResponseVo(100, "用户不存在").toString();
        }
    }

    @PostMapping(value = "/register")
    public String userRegister(@RequestBody JSONObject registerInfo) {
        JSONObject reqJson = registerInfo.getJSONObject("res");
        User user = new User();
        JSONObject userJson = reqJson.getJSONObject("userInfo");
        user.setOpenid(
                wxService.getOpenId(reqJson.getString("code"))
        );
        user.setGender(userJson.getInteger("gender"));
        user.setAvatarUrl(userJson.getString("avatarUrl"));
        user.setNickName(userJson.getString("nickName"));
        user.setWechatStr(reqJson.getString("encryptedData"));
        userRepository.save(user);
        return new ResponseVo().toString();
    }
}
